package com.zzyl.framework.interceptor.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;
import java.util.logging.Handler;
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){

            return true;

        }

        String token = request.getHeader("authorization");

        if (StringUtils.isEmpty(token)){

            throw new BaseException("认证失败");

        }

        Map<String,Object> claims = tokenService.parseToken(token);

        if (ObjectUtil.isNotEmpty(claims)){

            throw new BaseException("认证失败");


        }

        Long userId = MapUtil.get(claims , "userId" , Long.class);

        if (ObjectUtil.isEmpty(userId)){

            throw new BaseException("认证失败");

        }

        UserThreadLocal.set(userId);


        return true;



    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
